#include "dokermodel.h"
#include "qzip/qzipreader_p.h"
#include "qzip/qzipwriter_p.h"

#include <QtCore/qdebug.h>
#include <QtCore/qfileinfo.h>

DokerModel::DokerModel(QObject *parent) :
    QObject(parent)
{
    m_isModified = false;
    m_isUntitled = true;
    m_type = UnknownType;
}

bool DokerModel::contains(const QString &fileName)
{
    return m_files.contains(fileName);
}

void DokerModel::create()
{
    m_fullFileName = "untitled.dokz";
    m_isUntitled = true;
    m_files.insert("main.doks", qCompress(QByteArray()));
    emit fileAdded("untitled.dokz", "main.doks");
}

void DokerModel::editRequest(const QString &fileName)
{
    if (fileName.endsWith(".doks", Qt::CaseInsensitive))
        emit textEditRequested(fileName);
}

QByteArray DokerModel::fileData(const QString &fileName)
{
    if (m_files.contains(fileName))
        return qUncompress(m_files[fileName]);
    return QByteArray();
}

bool DokerModel::load(const QString &fullFileName)
{
    m_files.clear();
    if (fullFileName.endsWith(".dokp", Qt::CaseInsensitive))
    {

        m_type = ProjectType;
    }
    else if (fullFileName.endsWith(".dokz", Qt::CaseInsensitive))
    {
        QZipReader zip(fullFileName);
        if (!zip.exists() || !zip.isReadable())
            return false;
        const QString dokzName = QFileInfo(fullFileName).fileName();
        QList<QZipReader::FileInfo> files = zip.fileInfoList();
        foreach (QZipReader::FileInfo fileInfo, files)
        {
            m_files.insert(fileInfo.filePath, qCompress(zip.fileData(fileInfo.filePath)));
            emit fileAdded(dokzName, fileInfo.filePath);
        }
        m_type = BundleType;
    }
    else
    {
        qCritical() << tr("Wrong file:") << fullFileName;
        return false;
    }
    m_fullFileName = fullFileName;
    m_isUntitled = false;
    return true;
}

bool DokerModel::save()
{
    QZipWriter zip(m_fullFileName);
    if (!zip.isWritable())
        return false;
    foreach (QString fileName, m_files.keys())
    {
        zip.addFile(fileName, qUncompress(m_files[fileName]));
        emit modified(fileName, false);
    }
    zip.close();
    m_isModified = false;
    m_isUntitled = false;
    return true;
}

void DokerModel::setFileData(const QString &fileName, const QByteArray &data)
{
    m_files[fileName] = qCompress(data);
    emit modified(fileName, true);
    m_isModified = true;
}

void DokerModel::setFullFileName(const QString &fullFileName)
{
    if (m_isUntitled)
    {
        m_fullFileName = fullFileName;
        m_isUntitled = false;
    }
}
